package com.dengpp.pdform.config;

import android.view.View;

import com.dengpp.pdform.model.CascadingOption;
import com.dengpp.pdform.model.MediaFile;
import com.dengpp.pdform.model.MediaFileDialog;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AttributeConfig implements Serializable {
    private String key;//字段名
    private String title;//字段显示标题
    private AttributeType type;//字段类型
    private transient Object value;//默认值
    private List<String> options;//单选、多选、下拉的列表值
    private transient List<CascadingOption> cascadingOptions; // 多级选项数据
    private List<String> selectedCascadingValues; // 选中的多级值

    private transient Class<?> customViewClass;
    private transient Map<String, Object> customViewConfig;
    private transient View customViewInstance;
    // 序列化友好的字段
    private String stringValue;
    private List<String> listValue;
    private Map<String, Object> mapValue;
    private String mediaDialogTitle;
    private String[] mediaDialogItems;
    private String[] mediaDialogActions;
    private String customViewClassKey;
    private List<String> serializableOptions; // 可序列化的选项列表


    private boolean required;//是否必填
    private String hint;//用于设置提示文本
    private boolean editable;//是否开启编辑，默认开启
    /**
     * 是否隐藏，默认不隐藏;TextViewHolder、MultiLineViewHolder、NumberViewHolder提供设置，其他不提供效果
     * 使用场景：传递显示表单的时候如果需要联通id字段一同传递过来，但是也不想显示id值在表单中，
     * 则可以使用这个隐藏，然后保存按钮回调过去提取出传递的id值进行属性的修改
     */
    private boolean ishide;
    private int maxLines;//多行文本设置最大行数
    private String dateFormat;//日期框设置，如： .setDateFormat("yyyy-MM-dd")

    private String validationRule; // 验证规则
    private String validationMessage; // 验证失败提示信息
    private int minValue; // 最小值（用于数字）
    private int maxValue; // 最大值（用于数字）
    private int maxLength; // 最大长度（用于文本）

    /**
     * 多媒体按钮
     */
    private transient MediaFileDialog mediaFileDialog;
    private int mediaSpanCount = 3;//多媒体网格设置，默认3

    public enum AttributeType {
        TEXT,//文本框
        MULTI_LINE_TEXT,//多行文本框
        NUMBER,//数字
        TEXT_HIDE,//文本隐藏框
        MULTI_LINE_TEXT_HIDE,//多行文本隐藏框
        NUMBER_HIDE,//数字隐藏框
        RADIO,//单选框
        CHECKBOX,//复选框
        DATE,//日期
        DROPDOWN,//下拉框
        CASCADING_DROPDOWN, // 新增：多级下拉框
        MEDIA,//多媒体类型
        CUSTOM_VIEW//自定义视图类型
    }

    public AttributeConfig(String key, String title, AttributeType type) {
        this.key = key;
        this.title = title;
        this.type = type;
        this.editable = true;
        this.ishide = false;
        this.maxLines = 1;
    }

    // 验证相关方法
    public AttributeConfig setValidationRule(String validationRule) {
        this.validationRule = validationRule;
        return this;
    }

    public AttributeConfig setValidationMessage(String validationMessage) {
        this.validationMessage = validationMessage;
        return this;
    }

    public AttributeConfig setMinValue(int minValue) {
        this.minValue = minValue;
        return this;
    }

    public AttributeConfig setMaxValue(int maxValue) {
        this.maxValue = maxValue;
        return this;
    }

    public AttributeConfig setMaxLength(int maxLength) {
        this.maxLength = maxLength;
        return this;
    }

    // Builder 模式方法
    public AttributeConfig setValue(Object value) {
        this.value = value;
        // 设置序列化友好的值
        if (value == null) {
            this.stringValue = null;
            this.listValue = null;
            this.mapValue = null;
        } else if (value instanceof String) {
            this.stringValue = (String) value;
        } else if (value instanceof List) {
            // 对于 MediaFile 列表特殊处理
            if (!((List) value).isEmpty() && ((List) value).get(0) instanceof MediaFile) {
                this.listValue = convertMediaFilesToStringList((List<MediaFile>) value);
            } else {
                this.listValue = new ArrayList<>((List<String>) value);
            }
        } else if (value instanceof Map) {
            this.mapValue = new HashMap<>((Map<String, Object>) value);
        } else {
            this.stringValue = value.toString();
        }
        return this;
    }

    public AttributeConfig setOptions(List<String> options) {
        this.options = options;
        this.serializableOptions = options != null ? new ArrayList<>(options) : null;
        return this;
    }

    public AttributeConfig setRequired(boolean required) {
        this.required = required;
        return this;
    }

    public AttributeConfig setHint(String hint) {
        this.hint = hint;
        return this;
    }

    public AttributeConfig setIshide(boolean ishide) {
        this.ishide = ishide;
        return this;
    }

    public AttributeConfig setEditable(boolean editable) {
        this.editable = editable;
        return this;
    }

    public AttributeConfig setMaxLines(int maxLines) {
        this.maxLines = maxLines;
        return this;
    }

    public AttributeConfig setDateFormat(String dateFormat) {
        this.dateFormat = dateFormat;
        return this;
    }


    public AttributeConfig setMediaSpanCount(int mediaSpanCount) {
        this.mediaSpanCount = mediaSpanCount;
        return this;
    }

    // Getters
    public int getMediaSpanCount() {
        return mediaSpanCount;
    }

    public String getKey() {
        return key;
    }

    public String getTitle() {
        return title;
    }

    public AttributeType getType() {
        return type;
    }

    public Object getValue() {
        // 如果 value 为 null（反序列化后），尝试从序列化字段恢复
        if (value == null) {
            if (stringValue != null) {
                value = stringValue;
            } else if (listValue != null) {
                // 判断是否是 MediaFile 列表
                if (type == AttributeType.MEDIA) {
                    value = convertStringListToMediaFiles(listValue);
                } else {
                    value = new ArrayList<>(listValue);
                }
            } else if (mapValue != null) {
                value = new HashMap<>(mapValue);
            }
        }
        return value;
    }

    public List<String> getOptions() {
        // 如果 options 为 null（反序列化后），尝试从序列化字段恢复
        if (options == null && serializableOptions != null) {
            this.options = new ArrayList<>(serializableOptions);
        }
        return options;
    }

    public boolean isRequired() {
        return required;
    }

    public String getHint() {
        return hint;
    }

    public boolean isEditable() {
        return editable;
    }

    public boolean isHide() {
        return ishide;
    }

    public int getMaxLines() {
        return maxLines;
    }

    public String getDateFormat() {
        return dateFormat;
    }

    // Getters
    public String getValidationRule() {
        return validationRule;
    }

    public String getValidationMessage() {
        return validationMessage;
    }

    public int getMinValue() {
        return minValue;
    }

    public int getMaxValue() {
        return maxValue;
    }

    public int getMaxLength() {
        return maxLength;
    }


    // 如果需要支持 cascadingOptions 的序列化，可以添加以下字段和方法
    private List<CascadingOption> serializableCascadingOptions;

    // 设置多级选项的 Builder 方法
    public AttributeConfig setCascadingOptions(List<CascadingOption> cascadingOptions) {
        this.cascadingOptions = cascadingOptions;
        // 确保 CascadingOption 实现 Serializable
        this.serializableCascadingOptions = cascadingOptions != null ?
                new ArrayList<>(cascadingOptions) : null;
        return this;
    }

    // 在 AttributeConfig.java 中修改 setSelectedCascadingValues 方法
    public AttributeConfig setSelectedCascadingValues(List<String> selectedCascadingValues) {
        if (selectedCascadingValues != null) {
            // 创建新的可变 ArrayList，而不是直接使用传入的列表
            this.selectedCascadingValues = new ArrayList<>(selectedCascadingValues);
        } else {
            this.selectedCascadingValues = null;
        }
        return this;
    }

    // 添加一个方法来更新单个级别的选择
    public void updateCascadingSelection(int level, String value) {
        if (selectedCascadingValues == null) {
            selectedCascadingValues = new ArrayList<>();
        }

        // 确保列表足够长
        while (selectedCascadingValues.size() <= level) {
            selectedCascadingValues.add(null);
        }

        selectedCascadingValues.set(level, value);

        // 如果清除了某一级，也要清除后续级别
        if (value == null) {
            for (int i = level + 1; i < selectedCascadingValues.size(); i++) {
                selectedCascadingValues.set(i, null);
            }

            // 移除末尾的 null 值，保持列表整洁
            while (!selectedCascadingValues.isEmpty() && selectedCascadingValues.get(selectedCascadingValues.size() - 1) == null) {
                selectedCascadingValues.remove(selectedCascadingValues.size() - 1);
            }
        }
    }

    // 获取特定级别的选中值
    public String getCascadingValueAt(int level) {
        if (selectedCascadingValues == null || selectedCascadingValues.size() <= level) {
            return null;
        }
        return selectedCascadingValues.get(level);
    }

    // Getter 方法
    public List<CascadingOption> getCascadingOptions() {
        // 如果 cascadingOptions 为 null（反序列化后），尝试从序列化字段恢复
        if (cascadingOptions == null && serializableCascadingOptions != null) {
            this.cascadingOptions = new ArrayList<>(serializableCascadingOptions);
        }
        return cascadingOptions;
    }

    public List<String> getSelectedCascadingValues() {
        return selectedCascadingValues;
    }


    // ==================== 自定义视图相关方法 ====================

    public AttributeConfig setCustomViewClass(Class<?> customViewClass) {
        this.customViewClass = customViewClass;
        if (customViewClass != null) {
            this.customViewClassKey = "custom_" + this.key;
        }
        return this;
    }

    public AttributeConfig setCustomViewConfig(Map<String, Object> customViewConfig) {
        this.customViewConfig = customViewConfig;
        return this;
    }

    public Class<?> getCustomViewClass() {
        return customViewClass;
    }

    public Map<String, Object> getCustomViewConfig() {
        return customViewConfig;
    }

    public View getCustomViewInstance() {
        return customViewInstance;
    }

    public void setCustomViewInstance(View customViewInstance) {
        this.customViewInstance = customViewInstance;
    }

    public String getCustomViewClassKey() {
        return customViewClassKey;
    }

    // ==================== MediaFileDialog 处理方法 ====================

    public AttributeConfig setMediaFileDialog(MediaFileDialog mediaFileDialog) {
        this.mediaFileDialog = mediaFileDialog;

        // 同时存储可序列化的数据
        if (mediaFileDialog != null) {
            this.mediaDialogTitle = mediaFileDialog.getTitle();
            this.mediaDialogItems = mediaFileDialog.getItems();
            this.mediaDialogActions = mediaFileDialog.getCurrentAction();
        } else {
            this.mediaDialogTitle = null;
            this.mediaDialogItems = null;
            this.mediaDialogActions = null;
        }

        return this;
    }

    public MediaFileDialog getMediaFileDialog() {
        // 如果 mediaFileDialog 为 null（反序列化后），尝试从序列化字段恢复
        if (mediaFileDialog == null && mediaDialogTitle != null) {
            mediaFileDialog = new MediaFileDialog();
            mediaFileDialog.setTitle(mediaDialogTitle);
            mediaFileDialog.setItems(mediaDialogItems);
            mediaFileDialog.setCurrentAction(mediaDialogActions);
        }
        return mediaFileDialog;
    }
    // ==================== 序列化恢复方法 ====================

    public void restoreAfterSerialization() {
        // 恢复 value
        getValue();

        // 恢复 MediaFileDialog
        getMediaFileDialog();

        // 恢复 options
        getOptions();

        // 恢复 cascadingOptions（如果需要）
        // 注意：CascadingOption 也需要实现 Serializable
        if (cascadingOptions == null && serializableCascadingOptions != null) {
            // 这里需要实现 cascadingOptions 的恢复逻辑
            // 暂时留空，需要时再实现
        }
    }

    // ==================== 辅助方法 ====================

    private List<String> convertMediaFilesToStringList(List<MediaFile> mediaFiles) {
        List<String> result = new ArrayList<>();
        for (MediaFile mediaFile : mediaFiles) {
            String serialized = mediaFile.getPath() + "|" +
                    mediaFile.getType().name() + "|" +
                    (mediaFile.getName() != null ? mediaFile.getName() : "") + "|" +
                    (mediaFile.getThumbnail() != null ? mediaFile.getThumbnail() : "");
            result.add(serialized);
        }
        return result;
    }

    private List<MediaFile> convertStringListToMediaFiles(List<String> stringList) {
        List<MediaFile> result = new ArrayList<>();
        for (String serialized : stringList) {
            String[] parts = serialized.split("\\|", 4);
            if (parts.length >= 2) {
                MediaFile mediaFile = new MediaFile(parts[0], MediaFile.MediaType.valueOf(parts[1]));
                if (parts.length > 2 && !parts[2].isEmpty()) {
                    mediaFile.setName(parts[2]);
                }
                if (parts.length > 3 && !parts[3].isEmpty()) {
                    mediaFile.setThumbnail(parts[3]);
                }
                result.add(mediaFile);
            }
        }
        return result;
    }

}
